package org.example.shop.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
import org.example.shop.pojo.UserInfo;
import org.example.shop.service.MailService;
import org.example.shop.service.UserService;
import org.example.shop.shiro.UserToken;
import org.example.shop.vo.ApiResponse;
import org.example.shop.vo.UserReg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonObjectSerializer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@CrossOrigin // 允许跨域
public class UserController {
    private UserService userService;
    private MailService mailService;
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @GetMapping("/query")
    public ApiResponse query(String name) {
        UserInfo userInfo = userService.findByName(name);
        if (null != userInfo) {
            // 将密码职位null
            userInfo.setPassword(null);
        }
        return new ApiResponse().setCode(0).setData(userInfo);
    }

    @GetMapping("/send-code")
    public ApiResponse sendCode(String email) {
        ApiResponse res = new ApiResponse().setCode(0);
        if (StringUtils.isEmpty(email)) {
            return res.setCode(1).setMessage("邮箱地址为空");
        }
        StringBuffer code = new StringBuffer();
        Random r = new Random();
        for (int i = 0; i < 6; i++) {
            code.append(r.nextInt(10));
        }
        // 保存code到redis 过期时间设为 3min
        stringRedisTemplate.opsForValue().set("code:" + email, code.toString(), 3, TimeUnit.MINUTES);

        if (mailService.sendVerifyCode(email, code.toString())) {
            return res;
        }
        return res.setCode(2).setMessage("发送邮件失败");
    }

    @PostMapping("/create-with-code")
    public ApiResponse createWithCode(@RequestBody UserReg userReg) {
        ApiResponse res = new ApiResponse().setCode(1);
        if (StringUtils.isEmpty(userReg.getCode())) {
            return res.setMessage("验证码为空");
        }
        if (StringUtils.isEmpty(userReg.getUsername()) || !StringUtils.hasLength(userReg.getPassword())) {
            return res.setMessage("参数用户名和密码都允许为空");
        }
        // 验证 验证码是否正确
        String code = stringRedisTemplate.opsForValue().get("code:" + userReg.getUsername());
        if (code == null || !code.equals(userReg.getCode())) {
            return res.setMessage("验证码不正确");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(userReg.getUsername()).setPassword(userReg.getPassword());
        userInfo = userService.save(userInfo);
        if (null != userInfo) {
            userInfo.setPassword(null);
        }
        return res.setCode(0).setData(userInfo);
    }

    @PostMapping("/create")
    public ApiResponse create(@RequestBody UserReg userReg) {
        ApiResponse res = new ApiResponse().setCode(1);
        if (StringUtils.isEmpty(userReg.getUsername()) || !StringUtils.hasLength(userReg.getPassword())) {
            return res.setMessage("参数用户名和密码都允许为空");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(userReg.getUsername()).setPassword(userReg.getPassword());
        userInfo.setStatus(1);
        try {
            userInfo = userService.save(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return res.setCode(1).setMessage(e.getMessage());
        }
        if (null != userInfo) {
            userInfo.setPassword(null);
        }
        // 需要发送验证码 ?
//        发送需求到消息队列中
//        实际token应该随机生成 并且保存到redis或者数据库中 用于下一步的验证
        mailService.sendVerifyEmailMessage(userReg.getUsername(), "xxakjdafjefiuebiuadifareg");
        return res.setCode(0).setData(userInfo);
    }

    @RequestMapping("/verify")
    public String verify(String token) {
        // 原则 应该查询redis或者数据库值类的 判断token是否正确
        // 已经更新用户的状态
        return "success," + token;
    }


    @PostMapping("/login")
    public ApiResponse login(@RequestBody UserReg loginData) {
        ApiResponse response = new ApiResponse();
        UserInfo userinfo = userService.login(loginData.getUsername(), loginData.getPassword());
        if (userinfo == null) {
            return response.setCode(1).setMessage("用户名或者密码错误");
        }
        UserToken token = new UserToken();
        token.setUserInfo(userinfo);
        token.createToken();
        Gson gson = new Gson();

        // 将token和用户信息保存到redis中
        stringRedisTemplate.opsForValue().set(token.getToken(), gson.toJson(token), 30, TimeUnit.MINUTES);
        return response.setCode(0).setData(token);
    }
}
